package org.opencv.LoadObj;

import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import org.opencv.android.JavaCameraView;

import com.bieyang.anjia.R;
import com.bieyang.anjia.module.FileModel;
import com.bieyang.anjia.net.FileLoadManager;
import com.bieyang.anjia.net.FileLoadManager.UploadCallback;
import com.bieyang.anjia.ui.activity.App;
import com.bieyang.anjia.utils.Constants;
import com.bieyang.anjia.utils.Show;
import com.bieyang.anjia.utils.SubUtils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.hardware.Camera.PictureCallback;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;

@SuppressLint("HandlerLeak")
public class CameraCtrlView extends JavaCameraView implements PictureCallback {
	private String filePath;
	private Context context;
	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case Constants.GET_TOKEN_SUCEESS:
				upLoadAlarm(msg);
				break;
			case Constants.GET_TOKEN_FAILED:
				System.out.println("GET_TOKEN_FAILED");
				Show.toast(context, R.string.internet_exception);
				break;
			default:
				break;
			}
		};
	};

	/**
	 * 报警
	 * 
	 * @param msg
	 */
	private void upLoadAlarm(Message msg) {
		FileModel model = (FileModel) msg.obj;
		if (model.filePath.contains("take31")) {
			model.alarmType = "take31";
		} else if (model.filePath.contains("take32")) {
			model.alarmType = "take32";
		} else if (model.filePath.contains("take33")) {
			model.alarmType = "take33";
		} else {
			model.alarmType = "take1";
		}
		FileLoadManager.uploadByPath(model, new UploadCallback() {

			@Override
			public void callback(int fileSize, String key, String fileType) {
				SubUtils subUtils = new SubUtils();
				subUtils.upLoadFilePath(fileSize, key, fileType, context);
				subUtils.clearFile(context);
			}
		});
	}

	public CameraCtrlView(Context context, AttributeSet attrs) {
		super(context, attrs);
		this.context = context;
	}

	public void setResolution() {
		// disconnectCamera();
		// Log.i(TAG,"mMaxWidth: "+mMaxWidth+",mMaxHeight: "+mMaxHeight);

		// List<Size> ResolutionList =
		// mCamera.getParameters().getSupportedPictureSizes();
		/*
		 * Log.i(TAG,"ResolutionList.size: "+ResolutionList.size());
		 * ListIterator<Size> itRel = ResolutionList.listIterator();
		 * 
		 * while(itRel.hasNext()){ Log.i(TAG,"Resolution Setting..."); Size
		 * element = itRel.next(); if (element.width<=800 && element.width >=
		 * 600){ mMaxWidth = element.width; mMaxHeight = element.height;
		 * Log.i(TAG,"mMaxWidth: "+mMaxWidth+",mMaxHeight: "+mMaxHeight);
		 * return; } }
		 * Log.i(TAG,"mMaxWidth: "+mMaxWidth+",mMaxHeight: "+mMaxHeight);
		 */
		mMaxWidth = 800;
		mMaxHeight = 600;
		// connectCamera(getWidth(),getHeight());
	}

	/**
	 * 拍摄照片
	 * 
	 * @param filePath
	 *            文件路径
	 */
	public void takePicture(final String filePath) {
		// Log.i(TAG,"Taking Picture");
		this.filePath = filePath;
		Camera.Parameters pa = mCamera.getParameters();
		List<Camera.Size> sizeList = pa.getSupportedPictureSizes();

		if (null == sizeList || 0 == sizeList.size()) {

		} else if (1 == sizeList.size()) {
			Iterator<Camera.Size> it = sizeList.iterator();
			while (it.hasNext()) {
				Camera.Size size = it.next();
				pa.setPictureSize(size.width, size.height);
			}
		} else {
			int width = 1920, height = 0;
			Iterator<Camera.Size> it = sizeList.iterator();
			while (it.hasNext()) {
				Camera.Size size = it.next();
				Log.d("qiniu", size.width + "--" + size.height);
				if (width > size.width) {
					width = size.width;
					height = size.height;
				}
			}
			pa.setPictureSize(width, height);

			Log.d("qiniu", "width=" + width + "height=" + height);
		}
		List<String> flashList = pa.getSupportedFlashModes();
		if (flashList != null) {
			if (flashList.contains(Parameters.FOCUS_MODE_AUTO)) {
				pa.setFlashMode(Parameters.FOCUS_MODE_AUTO);
			}
		}
		try {
			mCamera.setParameters(pa);
		} catch (Exception e) {
			Log.d("qiniu", e.toString() + "----");
		}
		mCamera.setPreviewCallback(null);
		mCamera.autoFocus(null);
		mCamera.takePicture(null, null, this);
	}

	@Override
	public void onPictureTaken(byte[] data, Camera camera) {
		mCamera.startPreview();
		mCamera.setPreviewCallback(this);
		saveToSDCard(data); // 保存图片到sd卡中
	}

	/**
	 * 将拍下来的照片存放在SD卡中
	 * 
	 * @param data
	 * @throws IOException
	 */
	public void saveToSDCard(final byte[] data) {
		new Thread(new Runnable() {

			@Override
			public void run() {
				Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0,
						data.length);
				int w = bitmap.getWidth();
				int h = bitmap.getHeight();
				Bitmap newb = Bitmap.createBitmap(w, h, Config.ARGB_8888);
				Canvas cv = new Canvas(newb);
				Paint p = new Paint();
				p.setFilterBitmap(true);
				cv.drawBitmap(bitmap, 0, 0, p);
				Bitmap mark = BitmapFactory.decodeResource(
						context.getResources(), R.drawable.anplus);
				int w1 = mark.getWidth();
				int h1 = mark.getHeight();
				if (w > 320) {
					mark = Bitmap.createScaledBitmap(mark, w1, h1, true);
				} else {
					mark = Bitmap.createScaledBitmap(mark, w1 * 1 / 2,
							h1 * 1 / 2, true);
				}
				p.setAlpha(100);
				cv.drawBitmap(mark, w - mark.getWidth() - 10,
						h - mark.getHeight() - 10, p);
				cv.save(Canvas.ALL_SAVE_FLAG);
				cv.restore();
				BufferedOutputStream bos = null;
				try {
					bos = new BufferedOutputStream(new FileOutputStream(
							filePath));
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				newb.compress(Bitmap.CompressFormat.JPEG, 100, bos);
				try {
					if (null != bos) {
						bos.close();
					}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} // 关闭输出流
				newb.recycle();
				mark.recycle();
				bitmap.recycle();
				FileModel model = new FileModel();
				model.filePath = filePath;
				App.netManager.getToken(mHandler, model, context);
			}
		}).start();

	}

	/**
	 * 开启闪光灯
	 */
	public void flashModeOn() {
		Camera.Parameters pa = mCamera.getParameters();
		List<String> flashList = pa.getSupportedFlashModes();
		if (flashList != null) {
			if (flashList.contains(Parameters.FLASH_MODE_TORCH)) {
				pa.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
				mCamera.setParameters(pa);
				mCamera.startPreview();
			}
		}
	}

	/**
	 * 获取Camera实例
	 */
	public Camera getCamera() {
		return mCamera;
	}

	/**
	 * 关闭闪光灯
	 */
	public void flashModeOff() {
		Camera.Parameters pa = mCamera.getParameters();
		List<String> flashList = pa.getSupportedFlashModes();
		if (flashList != null) {
			if (flashList.contains(Parameters.FLASH_MODE_OFF)) {
				pa.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
				mCamera.setParameters(pa);
				mCamera.startPreview();
			}
		}
	}
}
